package com.ding.manager.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ding.manager.config.DTConstant;
import com.ding.manager.controller.base.ManagerBaseController;
import com.ding.manager.service.ApproveService;
import com.ding.manager.util.*;
import com.dingtalk.oapi.lib.aes.DingTalkEncryptor;
import com.dingtalk.oapi.lib.aes.Utils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 钉钉回调
 * 钉钉jsapi config
 */
@Controller
@RequestMapping(value = "/approve")
public class DTUtilController extends ManagerBaseController {

    @Resource(name = "approveService")
    private ApproveService approveService;

    @RequestMapping(value = "/list")
    @ResponseBody
    public ResponseEntity getApproveList(){
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        }catch (Exception e){
            logger.info("获取审批列表失败", e);
            responseEntity.setMsg("获取审批列表失败!");
            responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
        }

        return responseEntity;

    }

    //钉钉回调
    @RequestMapping("/instanceCallback")
    @ResponseBody
    public Map<String, String> callback(@RequestParam(value = "signature", required = false) java.lang.String signature,
                                             @RequestParam(value = "timestamp", required = false) java.lang.String timestamp,
                                             @RequestParam(value = "nonce", required = false) java.lang.String nonce,
                                             @RequestBody(required = false) JSONObject json, HttpServletRequest request) {
        Map properties = request.getParameterMap();

        java.lang.String params = " signature:"+signature + " timestamp:"+timestamp +" nonce:"+nonce+" json:"+json;
        String plainText = "";
        try {
            logger.info("begin /callback"+params);
            DingTalkEncryptor dingTalkEncryptor = new DingTalkEncryptor("123456", "1234567890123456789012345678901234567890123",
                    DTConstant.CORPID);

            //从post请求的body中获取回调信息的加密数据进行解密处理
            String encryptMsg = json.getString("encrypt");
            plainText = dingTalkEncryptor.getDecryptMsg(signature, timestamp, nonce, encryptMsg);
            JSONObject obj = JSON.parseObject(plainText);

            //根据回调数据类型做不同的业务处理
            java.lang.String eventType = obj.getString("EventType");
            if (DTConstant.EVENT_CHECK_CREATE_SUITE_URL.equals(eventType)) {
                logger.info("验证新创建的回调URL有效性: " + plainText);
            } else if (DTConstant.EVENT_CHECK_UPADTE_SUITE_URL.equals(eventType)) {
                logger.info("验证更新回调URL有效性: " + plainText);
            } else if(DTConstant.BPMS_INSTANCE_CHANGE.equals(eventType)){
                logger.info("bpms_instance_change的回调: " + plainText);
                approveService.updateProjStatus(obj.getString("processInstanceId"));
            }else if(DTConstant.BPMS_TASK_CHANGE.equals(eventType)){
                logger.info("bpms_task_change的回调: " + plainText);
                approveService.updateProjStatus(obj.getString("processInstanceId"));
            }else {
                // 其他类型事件处理
            }

            // 返回success的加密信息表示回调处理成功
            return dingTalkEncryptor.getEncryptedMap("success", System.currentTimeMillis(), Utils.getRandomStr(8));
        } catch (Exception e) {
            //失败的情况，应用的开发者应该通过告警感知，并干预修复
            logger.error("process callback failed！"+params,e);
            logger.error("instance callback failed！"+ plainText,e);
            return null;
        }

    }




    //钉钉jsapi config
    @RequestMapping(value = "/getConfig", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity getConfig() {
        PageData pd = this.getPageData();
        if(StringUtils.isNotEmpty(pd.getString("finsh"))){
            System.out.println("--------------------------------------------------------");
            System.out.println(pd.getString("finsh"));
            System.out.println("--------------------------------------------------------");
            return new ResponseEntity();
        }

        Map<String, String> config = new HashMap<>();
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String ticket = GetTicket();
        String string1 = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=http://xumy.ngrok.xiaomiqiu.cn/routers/login";
        String signature = SHA1.encode(string1);
        config.put("agentId", "212153413");
        config.put("corpId", DTConstant.CORPID);
        config.put("timeStamp", timestamp);
        config.put("nonceStr", noncestr);
        config.put("signature", signature);
        ResponseEntity res = new ResponseEntity();
        res.put("config",config);
        return res;
    }

    private String GetTicket()
    {
        String ticket = "";
        String json = HttpUtils.sendGet("https://oapi.dingtalk.com/get_jsapi_ticket","access_token="+DTConstant.ACCESS_TOKEN);
        JSONObject jsonObject = JSON.parseObject(json);
        String msg = (String)jsonObject.get("errmsg");
        if("ok".equals(msg)){
            ticket = (String)jsonObject.get("ticket");
        }
        return ticket;
    }
    

}
